<!--
  * 订退单
  *
-->
<template>
  <a-drawer :title="formTitle" :open="visible" @close="onClose">
    <template #closeIcon>
      <close @on-close="onClose" />
    </template>
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ sm: 4, lg: 6 }">
      <!---------- 基本信息 begin ----------->
      <a-card title="基本信息" class="smart-margin-bottom10">
        <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
          <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
            <a-form-item label="开单仓库" name="warehouse_id" required>
              <Select name="Warehouse" :fetch-params="selectFetchParams.warehouse" v-model:value="form.warehouse_id" placeholder="请选择仓库" @change="onChangeWarehouse" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
            <a-form-item label="业务员" name="salesman_id" required>
              <Select name="Salesman" v-model:value="form.salesman_id" placeholder="请选择业务员" @change="onChangeSalesman" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
            <a-form-item label="门店名称" name="store_id" required>
              <Select name="Store" v-model:value="form.store_id" :fetch-params="storeSelectFetchParams" placeholder="请选择门店" @change="onChangeStore" :disabled="isDisabled" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
            <a-form-item label="结算方式" name="payment_type" required>
              <EnumSelect enum-name="RECEIVE_TYPE_ENUM" v-model:value="form.payment_type" placeholder="请选择结算方式" disabled />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
            <a-form-item label="订单备注">
              <a-input v-model:value="form.remark" placeholder="请输入整单备注" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
      <!---------- 基本信息 end ----------->
      <!---------- 商品信息 begin ----------->
      <a-card title="商品信息" class="smart-margin-bottom10">
        <a-table size="small" :dataSource="form.detail" :columns="columns" :scroll="{ x: 'max-content' }" :pagination="false" :showSorterTooltip="false">
          <template #bodyCell="{ text, record, column, index }">
            <template v-if="column.dataIndex === 'index'">
              <div class="form-table-index">
                <span>{{ index + 1 }}</span>
                <div class="form-table-index-btn-wrap">
                  <div class="form-table-index-btn">
                    <div class="form-table-index-btn-item" @click="addFormDetail(index)">+</div>
                    <div class="form-table-index-btn-item" @click="delFormDetail(index)">-</div>
                  </div>
                </div>
              </div>
            </template>
            <template v-if="column.dataIndex === 'type'">
              <a-form-item
                class="form-table-item"
                required
                :name="['detail', index, 'type']"
                :rules="[
                  {
                    required: true,
                    message: '请选择商品类型',
                    validator: (rule, value, callback) => validatorGoodsTable(record, rule, value, callback)
                  }
                ]"
              >
                <a-select v-model:value="record.type" placeholder="请选择" @change="handleGoodsTypeChange(record, index)">
                  <template #suffixIcon> </template>
                  <a-select-option :value="6"> <a-tag color="orange" :bordered="false">订退</a-tag> </a-select-option>
                </a-select>
              </a-form-item>
            </template>
            <template v-if="column.dataIndex === 'goods_name'">
              <a-form-item class="form-table-item" required :name="['detail', index, 'goods_name']" :rules="[{ required: true, message: '请添加商品', validator: (rule, value, callback) => validatorGoodsTable(record, rule, value, callback) }]">
                <!-- 使用 a-tooltip 显示-->
                <a-tooltip v-if="text">
                  <template #title>{{ text }}</template>
                  <a-input :value="text" readonly placeholder="商品名称、助记码" size="small">
                    <template #suffix>
                      <a-button @click="showGoodsSelectModal(index)" type="link">多选</a-button>
                    </template>
                  </a-input>
                </a-tooltip>
                <a-input :value="text" readonly placeholder="商品名称、助记码" size="small" v-else>
                  <template #suffix>
                    <a-button @click="showGoodsSelectModal(index)" type="link">多选</a-button>
                  </template>
                </a-input>
              </a-form-item>
            </template>
            <template v-if="column.dataIndex === 'img'">
              <a-image :width="text ? 30 : 50" :src="record.goods_name ? text || failImg : ''" />
            </template>

            <template v-if="column.dataIndex === 'num'">
              <a-form-item
                class="form-table-item"
                :name="['detail', index, 'num']"
                :rules="[
                  {
                    required: true,
                    message: '请输入商品数量',
                    validator: (rule, value, callback) => validatorGoodsTable(record, rule, value, callback)
                  }
                ]"
              >
                <a-input-number v-model:value="record.num" :min="1" :precision="0" @change="(value) => handleChange(record, value)" />
              </a-form-item>
            </template>
            <template v-if="column.dataIndex === 'real_price'">
              {{ formatPrice(text) }}
            </template>
            <template v-if="column.dataIndex === 'total'">
              {{ _.floor(_.multiply(record.num ?? 0, record.real_price ?? 0), 2) }}
            </template>
            <template v-if="column.dataIndex === 'remark'">
              <a-form-item class="form-table-item">
                <a-input v-model:value="record.remark" />
              </a-form-item>
            </template>
          </template>
        </a-table>
        <a-row class="goods-table-footer" :gutter="[0, 10]">
          <a-col :span="24">
            <a-row :gutter="10" justify="end">
              <a-col v-if="_.every(form.detail, _.isEmpty)">
                <span>未选择商品</span>
              </a-col>
              <template v-else>
                <a-col v-for="item in _(form.detail).map('type').uniq().compact().sort().value()">
                  <goods-type-tag :value="item" />
                  {{ _.sumBy(_.filter(form.detail, { type: item }), 'num') || 0 }}
                </a-col>
              </template>
            </a-row>
          </a-col>
          <a-col :span="24">
            <a-row :gutter="10" justify="justify-between" align="middle">
              <a-col :xs="24" :lg="12"> </a-col>
              <a-col :xs="24" :lg="12" style="text-align: right"> 订退货：¥{{ _.floor(returnAmount, 2) || 0 }} 合计：¥{{ _.floor(totalAmount, 2) || 0 }} </a-col>
            </a-row>
          </a-col>
        </a-row>
      </a-card>
      <!---------- 商品信息 end ----------->
    </a-form>
    <GoodsSelectModal ref="goodsSelectModalRef" :order-type="3" :book-type="2" @confirm="onSelectGoods" />
    <template #footer>
      <div class="smart-table-operate-block">
        <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">提交</a-button>
      </div>
    </template>
  </a-drawer>
</template>
<script setup lang="ts">
import { message, Modal } from 'ant-design-vue'
import { useLoadingStore } from '@/store/modules/loading-store'
import _ from 'lodash'
import { errorSentry } from '@/lib/error-sentry'
import { orderApi } from '@/api/business/sale/visiting-api'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { WAREHOUSE_ATTRIBUTE_TYPE, WAREHOUSE_TYPE } from '@/constants/business/storage/warehouse/warehouse-const'
import GoodsSelectModal from './goods-select-modal.vue'
import GoodsTypeTag from '@/components/business/goods-type-tag/index.vue'
import EnumSelect from '@/components/framework/enum-select/index.vue'
import Select from '@/components/business/select/index.vue'
import failImg from '@/assets/images/notice/failImg.png'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { createVNode } from 'vue'
const loadingStore = useLoadingStore()
// emit
const emit = defineEmits(['reloadList'])

// 组件ref
const formRef = ref()

const formDefault = {
  // 仓库
  warehouse_id: undefined,
  // 业务员
  salesman_id: undefined,
  // 门店
  store_id: undefined,
  // 结算方式
  payment_type: 3,
  // 备注
  remark: '',
  // 商品信息
  detail: []
}
const form = ref({ ...formDefault })
onMounted(() => {
  form.value.detail.push({ type: 6 })
})
const rules = {
  warehouse_id: [{ required: true, message: '请选择仓库', trigger: 'change' }],
  salesman_id: [{ required: true, message: '请选择业务员', trigger: 'change' }],
  store_id: [{ required: true, message: '请选择门店', trigger: 'change' }],
  payment_type: [{ required: true, message: '请选择结算方式', trigger: 'change' }]
}

// 商品表格自定义校验
const validatorGoodsTable = (rowData, rule, value, callback) => {
  if (_.isEmpty(rowData) || !_.isNil(value)) callback()
  else {
    callback(rule.message)
  }
}
// 用于存储初始数据的ref
const initialFormData = ref(null)
// 是否展示抽屉
const visible = ref(false)

function showDrawer(rowData) {
  form.value = _.cloneDeep(formDefault)

  if (rowData.id && !_.isEmpty(rowData)) {
    // 保存初始数据
    initialFormData.value = {
      detail: rowData.detail.map((item) => ({
        id: item.id,
        num: item.num,
        real_price: item.real_price,
        remark: item.remark
      }))
    }
    form.value = _.pick(rowData, ['id', ...Object.keys(formDefault)])
    // 加载商品详情数据
    form.value.detail = rowData.detail.map((item) => {
      return {
        ...item,
        goods_name: item.goods?.goods_name,
        img: item.goods?.img,
        unit: item.spec?.unit_name,
        barcode: item.spec?.barcode,
        spec_name: item.spec?.spec_name,
        type: item.type, // 商品类型
        num: item.num, // 数量
        real_price: item.real_price, // 单价
        sale_price: item.sale_price,
        total_price: item.total_price,
        volume: Number(item.volume), // 体积
        weight: Number(item.weight), // 重量
        remark: item.remark // 备注
      }
    })
    form.value.detail.push({ type: 6 })
  }
  visible.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

function onClose() {
  form.value = formDefault
  deletedGoods.value = []
  visible.value = false
}

async function onSubmit() {
  const validItems = unref(form).detail.filter((item) => !_.isEmpty(item) && item.goods_id && item.num !== 0)
  if (validItems.length === 0) {
    message.error('请选择商品')
    return
  }
  form.value.detail = validItems
  await nextTick()
  formRef.value
    .validate()
    .then(async () => {
      loadingStore.show()
      try {
        if (unref(form).id) {
          const keys = ['id', 'book_order_id', 'book_order_detail_id', 'num', 'total_price', 'real_price', 'sale_price', 'goods_id', 'goods_spec_id', 'remark', 'type', 'volume', 'weight']
          unref(form).detail.forEach((item) => {
            item.total_price = _.floor(_.multiply(item.num, item.real_price), 2)
            item.volume = _.multiply(item.num, item.volume).toFixed(2)
            item.weight = _.multiply(item.num, item.weight).toFixed(2)
          })
          const specData = _(unref(form).detail)
            .concat(deletedGoods.value)
            .cloneDeep()
            .map((item) => {
              const result = _.pick(item, keys)

              // 如果是已删除的商品，直接标记并返回
              if (deletedGoods.value.some((good) => good.id === item.id)) {
                result.is_delete = 1
                return result
              }

              // 对于未删除的商品，检查是否有变化
              const initialItem = initialFormData.value.detail.find((init) => init.id === item.id)
              if (initialItem) {
                const fieldsToCheck = ['num', 'real_price', 'remark']
                let hasChanged = false

                // 检查是否有任何字段发生变化
                fieldsToCheck.forEach((field) => {
                  if (initialItem[field] !== item[field]) {
                    hasChanged = true
                  }
                })

                // 只有在有变化时才保留该数据项
                if (hasChanged) {
                  result.id = item.id
                  Object.assign(result, _.pick(item, fieldsToCheck))
                  return result
                }

                // 如果没有变化，返回null，后续会被过滤掉
                return null
              }

              // 如果是新增的商品（没有初始数据），直接返回
              return result
            })
            .filter((item) => item !== null) // 过滤掉没有变化的数据项

          const data = {
            ...unref(form),
            detail: JSON.stringify(specData),
            type: 1,
            order_type: 5,
            discounted_amount: totalAmount.value
          }
          await orderApi.edit(data)
        } else {
          const keys = ['book_order_id', 'book_order_detail_id', 'num', 'total_price', 'real_price', 'sale_price', 'goods_id', 'goods_spec_id', 'remark', 'type', 'volume', 'weight']
          unref(form).detail.forEach((item) => {
            item.total_price = _.floor(_.multiply(item.num, item.real_price), 2)
            item.volume = _.multiply(item.num, item.volume).toFixed(2)
            item.weight = _.multiply(item.num, item.weight).toFixed(2)
          })
          const specData = _(unref(form).detail)
            .cloneDeep()
            .map((item) => {
              return {
                ..._.pick(item, keys)
              }
            })
          const data = {
            ...unref(form),
            detail: JSON.stringify(specData),
            type: 1,
            order_type: 5,
            discounted_amount: totalAmount.value
          }
          await orderApi.create(data)
        }
        message.success('操作成功')
        onClose()
        emit('reloadList')
      } catch (error) {
        message.error(error.msg)
        errorSentry.captureError(error)
      } finally {
        loadingStore.hide()
      }
    })
    .catch((error) => {
      message.error('参数验证错误，请仔细填写表单数据!')
    })
}

defineExpose({
  showDrawer
})

// ----------------------------------  基本信息 begin  ----------------------------------
// Select组件查询参数
const selectFetchParams = {
  warehouse: {
    filter: {
      warehouse_type: WAREHOUSE_TYPE.FIXED.value,
      attribute_type: [WAREHOUSE_ATTRIBUTE_TYPE.WAREHOUSE.value, WAREHOUSE_ATTRIBUTE_TYPE.EXPIRED.value, WAREHOUSE_ATTRIBUTE_TYPE.TEMPORARY.value]
    },
    op: {
      warehouse_type: QUERY_FORM_OP['全等查询'],
      attribute_type: QUERY_FORM_OP['IN查询']
    },
    fields: 'id,name'
  },
  dealer: {
    fields: 'id,name'
  }
}

const storeSelectFetchParams = computed(() => {
  return {
    fields: 'id,store_name',
    salesman_id: unref(form).salesman_id,
    filter: {},
    op: {}
  }
})

function onChangeWarehouse(val) {
  if (val) {
    form.value?.id && deletedGoods.value.push(...form.value.detail.filter((item) => item.id))
    form.value.detail = []
    form.value.detail.push({ type: 6 })
  }
}

function onChangeSalesman(val) {
  if (val) {
    form.value?.id && deletedGoods.value.push(...form.value.detail.filter((item) => item.id))
    form.value.detail = []
    form.value.detail.push({ type: 6 })
  }
  form.value.store_id = undefined
}

function onChangeStore(val) {
  if (val) {
    form.value?.id && deletedGoods.value.push(...form.value.detail.filter((item) => item.id))
    form.value.detail = []
    form.value.detail.push({ type: 6 })
  }
}

// ----------------------------------  基本信息 end  ----------------------------------

// 商品选择弹窗
const goodsSelectModalRef = ref()
const modalIndex = ref(0)
// 记录点击多选按钮的表格行索引，插入数据时使用
function showGoodsSelectModal(index: number) {
  if (!form.value.warehouse_id) {
    message.error('仓库ID未加载完成，请稍后再试')
    return
  }

  if (!form.value.store_id) {
    message.error('门店ID未加载完成，请稍后再试')
    return
  }
  modalIndex.value = index
  goodsSelectModalRef.value.showModal({ warehouse_id: form.value.warehouse_id, store_id: form.value.store_id })
}

// 使用 ref 存储上一次的值，避免重复触发
const lastValues = ref(new Map())

const handleChange = async (record, value) => {
  // 获取当前记录的上一次值
  const lastValue = lastValues.value.get(record.id)

  // 如果值没有变化，直接返回
  if (lastValue === value) return

  // 更新上一次的值
  lastValues.value.set(record.id, value)

  const updateValue = (newValue) => {
    record.num = newValue
    lastValues.value.set(record.id, newValue)
  }

  if (record.num > Number(record.fulfilled_num)) {
    return new Promise((resolve) => {
      Modal.confirm({
        title: '确定退货？',
        icon: createVNode(ExclamationCircleOutlined),
        content: `退货数量大于已履约数量${record.fulfilled_num}${record.unit},确定退货？`,
        onOk() {
          updateValue(value)
          resolve(true)
        },
        onCancel() {
          updateValue(record.num)
          resolve(false)
        }
      })
    })
  } else {
    updateValue(value)
  }
}

// 记录已删除的商品
const deletedGoods = ref([])

// 商品选择回调
function onSelectGoods(goodsList) {
  if (goodsList.length === 0) return
  // 处理商品数据
  function handleGoodsData(rowData) {
    return {
      type: 6,
      book_order_detail_id: rowData.id,
      book_order_id: rowData.book_order_id,
      img: rowData.goods?.img,
      goods_name: rowData.goods?.goods_name,
      barcode: rowData.spec?.barcode,
      spec_name: rowData.spec?.spec_name,
      unit: rowData.spec?.unit_name,
      conversion_rate: rowData.spec?.conversion_rate,
      unit_type: rowData.spec?.unit_type,
      goods_id: rowData.spec?.goods_id,
      goods_spec_id: rowData.spec?.id,
      sale_price: rowData.sale_price,
      real_price: rowData.real_price,
      fulfilled_num: rowData.fulfilled_num,
      num: '',
      remark: ''
    }
  }
  // 如果当前索引值有数据则覆盖
  const rows = _.map(goodsList, handleGoodsData)
  if (unref(form).detail[modalIndex.value]) {
    if (unref(form).detail[modalIndex.value].id) {
      deletedGoods.value.push(form.value.detail[modalIndex.value])
    }
    form.value.detail.splice(modalIndex.value, 1, ...rows)
  } else {
    // 否则插入数据
    if (modalIndex.value === 0) {
      // 从modalIndex插入数据
      form.value.detail.splice(modalIndex.value, 0, ...rows)
    } else {
      // 从modalIndex插入数据
      form.value.detail.splice(modalIndex.value + 1, 0, ...rows)
    }
  }
  // 自动追加一个空行
  if (!_.isEmpty(_.last(unref(form).detail))) form.value.detail.push({ type: 6 })
}

// ----------------------------------  商品信息  ----------------------------------
// 表头配置
const columns = [
  {
    title: '序号',
    dataIndex: 'index'
  },
  {
    title: '类型',
    dataIndex: 'type',
    width: 60
  },
  {
    title: '商品名称',
    dataIndex: 'goods_name',
    width: 300
  },
  {
    title: '图片',
    dataIndex: 'img'
  },
  {
    title: '规格条码',
    dataIndex: 'barcode',
    width: 150
  },
  {
    title: '规格',
    dataIndex: 'spec_name',
    width: 60
  },
  {
    title: '单位',
    dataIndex: 'unit',
    width: 60
  },
  {
    title: '数量',
    dataIndex: 'num',
    width: 60
  },
  {
    title: '单价',
    dataIndex: 'real_price',
    width: 80
  },
  {
    title: '小计',
    dataIndex: 'total'
  },
  {
    title: '商品备注',
    dataIndex: 'remark'
  }
]

// 增加空行
function addFormDetail(index: number) {
  form.value.detail.splice(index + 1, 0, {})
}
// 删除行
function delFormDetail(index: number) {
  const formDetail = unref(form).detail // 获取当前的详情数组
  const item = formDetail[index] // 获取要删除的项

  // 检查是否只剩最后一条数据
  if (formDetail.length === 1) {
    message.error('不能删除最后一条数据！') // 提示用户
    return // 退出函数，不执行后续操作
  }

  // 如果是编辑状态，将删除的项加入已删除列表
  if (unref(form).id && item.id) {
    deletedGoods.value.push(item)
  }

  // 删除指定索引的元素
  formDetail.splice(index, 1)
}

// 类别选择
const handleGoodsTypeChange = (record, index) => {
  form.value.detail[index].real_price = record.type == 2 ? 0 : record.spec_sale_price
}
// ----------------------------------  商品合计  ----------------------------------
// 金额处理
const formatPrice = (price) => {
  // 检查 price 是否为有效的数字
  if (isNaN(price) || price === null || price === undefined) {
    return '0.00' // 或者返回其他默认值
  }

  // 将价格转换为浮点数
  price = parseFloat(price)

  // 格式化为最多6位小数的字符串
  let formattedPrice = price.toFixed(6)

  // 去除末尾多余的无效零
  formattedPrice = formattedPrice.replace(/(\.\d*?)0+$/, '$1')

  // 确保至少保留两位小数
  if (!formattedPrice.includes('.')) {
    formattedPrice += '.00'
  } else if (formattedPrice.split('.')[1].length < 2) {
    formattedPrice += '0'.repeat(2 - formattedPrice.split('.')[1].length)
  }

  return formattedPrice
}
// 订退货
const returnAmount = computed(() => {
  const list = _.filter(unref(form).detail, { type: 6 })
  return _.sumBy(list, (item) => _.multiply(item.num || 0, item.real_price || 0))
})
// 合计
const totalAmount = computed(() => {
  return returnAmount.value
})

// 是否禁用选择框
const isDisabled = computed(() => {
  // 如果是编辑操作，返回 false（不禁用）
  if (form.value.id) {
    return false
  }
  // 如果是新增操作，未选择，返回 true（禁用）
  return !form.value.salesman_id
})
// 表单标题
const formTitle = computed(() => (form.value.id ? '编辑' : '新增'))
</script>
<style scoped lang="less">
.form-table-item {
  margin-bottom: 0;
  max-width: 100%;
}
.form-table-index {
  width: 100%;
  height: 100%;
  overflow: hidden;
  text-align: center;
  .form-table-index-btn-wrap {
    display: none;
  }
  .form-table-index-btn {
    display: flex;
  }
  .form-table-index-btn-item {
    width: 50%;
    height: 100%;
    font-size: 14px;
    font-weight: bold;
    text-align: center;
    cursor: pointer;
    user-select: none;
  }
  .form-table-index-btn-item:hover {
    background: #f87171ff;
    color: white;
  }
}
.form-table-index:hover span {
  display: none;
}
.form-table-index:hover .form-table-index-btn-wrap {
  display: block;
}
</style>
